const randomUUID = () => {
  const hexDigits = "0123456789abcdef";
  let uuid = "";

  for (let i = 0; i < 36; i++) {
    if (i === 8 || i === 13 || i === 18 || i === 23) {
      uuid += "-";
    } else if (i === 14) {
      uuid += "4";
    } else if (i === 19) {
      uuid += hexDigits[Math.floor(Math.random() * 4) + 8];
    } else {
      uuid += hexDigits[Math.floor(Math.random() * 16)];
    }
  }
  return uuid;
};

const emulateRandomUUID = () => {
  if (!window.crypto.randomUUID) {
    window.crypto.randomUUID = function () {
      var randomPool = new Uint8Array(16); // ES6中可以用crypto.getRandomValues代替
      crypto.getRandomValues(randomPool);
      randomPool[6] &= 0x0f; // clear version
      randomPool[6] |= 0x40; // set to version 4
      randomPool[8] &= 0x3f; // clear variant
      randomPool[8] |= 0x80; // set to IETF variant
      var hex = randomPool.toString();
      return (
        hex.substring(0, 8) +
        "-" +
        hex.substring(8, 12) +
        "-4" +
        hex.substring(12, 16) +
        "-" +
        hex.substring(16, 20) +
        "-" +
        hex.substring(20)
      );
    };
  }
};

export { emulateRandomUUID, randomUUID };
